package MuleBackend;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import MuleGUI.BoardGUI;

import com.google.gson.Gson;

/**
 * GameDriver class starts the 
 * mule game
 * @author Jackson
 *
 */
public class GameDriver {
	

	public static Game game;
	
	/**
	 * loading method to load the game
	 * instantiates all the values with the old ones
	 */
	public static void loadGame() {
		
	File file = new File("SaveData.txt");
	Scanner scanner = null;
	
	try {
			scanner = new Scanner(file);
	} catch (IOException e) {
		System.out.println("File not found");
		System.exit(-1);
	}
	String gameCopy = scanner.nextLine();

	Game gamecopy = new Gson().fromJson(gameCopy, Game.class);
		
	ArrayList<Player> playerlist = gamecopy.getPlayerList();	
		for (Player play : playerlist) {
			game.addPlayer(play);
		}
		game.getStages().setPlayerList();
		game.generateMap(gamecopy.getMapNum());
		game.boardGUI.addMap();
		game.setBoard(gamecopy.getBoard());
		
		game.setDifficulty(gamecopy.getDifficulty());
		game.setMapNum(gamecopy.getMapNum());
		game.setRounds(gamecopy.getRounds());
		game.setNumPlayers(gamecopy.getNumPlayers());
		game.setRoundNumber(gamecopy.getRoundNumber());
		game.setCurrentPlayer(gamecopy.getCurrentPlayer());
		game.setCurrentStage(gamecopy.getCurrentStage());
		game.setStages(gamecopy.getStages());
		game.getStages().setPlayerList();
		ArrayList<Player> listofplayers = game.getPlayerList();
	
		for (Player play : listofplayers) {
			play.setLandsOwned();
			play.setRace(new ImageIcon(""+play.getRace()));
		}
		
		Land[][] lands = game.getLandsArray();
		
		for (int i=0;i< lands.length;i++) {
			for (int j=0; j<lands[i].length;j++) {
				if (lands[i][j].getOwner() != null) {
					for (Player play : listofplayers) {
						if (lands[i][j].getOwner().name.equals(play.name)) {
							play.addLand(lands[i][j]);
							game.boardGUI.colorLand(i,j, play.getColor());
						}
					}
				}
			}
		}
		
		game.getStages().startStage(game.getStages().getCurrentStage());
	}

	/**
	 * main method for running the mule game
	 * @param args
	 */
	public static void main(String[] args) {
		game = Game.getInstance();		
		game.showBoardGUI();
	}
}
